const fs = require('fs');
const path = require('path');
const postcss = require('postcss');
const sorting = require('postcss-sorting');

// 定义 PostCSS 插件
function formatCSSToOnePropertyPerLine() {
    return {
        postcssPlugin: 'format-css-to-one-property-per-line',
        OnceExit(css) {
            css.walkRules(rule => {
                // 确保每个规则后面有一个换行
                rule.raws.after = '\n';
                // 检查是否有大括号前的空格
                if (!rule.raws.between) rule.raws.between = ' ';

                rule.walkDecls(decl => {
                    // 确保每个声明前面有换行和两个空格的缩进
                    decl.raws.before = '\n  ';
                    // 确保每个声明之间有冒号和分号，并且没有额外的空格
                    decl.raws.between = ': ';
                    decl.raws.after = ';';
                });

                // 处理嵌套规则
                rule.walkRules(nestedRule => {
                    nestedRule.raws.before = '\n  ';
                    nestedRule.raws.between = ' ';
                });
            });
        }
    };
}

function removeExtraSpaces() {
    return {
        postcssPlugin: 'remove-extra-spaces',
        OnceExit(css) {
            css.walkDecls(decl => {
                // 移除冒号后的空格
                if (decl.raws.between && decl.raws.between.trim() === ':') {
                    decl.raws.between = ':';
                }

                // 确保分号前没有多余空格
                if (decl.raws.after && decl.raws.after.trim() === ';') {
                    decl.raws.after = ';';
                }
            });

            // 移除选择器和大括号之间的多余空格
            css.walkRules(rule => {
                if (rule.raws.between && rule.raws.between.trim() === '{') {
                    rule.raws.between = '{'; // 移除选择器和 { 之间的空格
                }
                if (rule.raws.after && rule.raws.after.trim() === '}') {
                    rule.raws.after = '}\n'; // 确保规则结束有换行符
                }
            });

            // 移除规则之间以及文件开头和末尾的多余空格
            css.raws.before = '';
            css.raws.after = '';
        }
    };
}

function minifyToOneLinePerSelector() {
    return {
        postcssPlugin: 'minify-to-one-line-per-selector',
        OnceExit(css) {
            let outputRules = [];
    
            css.walkRules((rule) => {
                // 移除选择器中的多余空白
                const selector = rule.selector.replace(/\s*\n\s*/g, ' ');
    
                // 构建单行声明字符串
                let declStr = '';
                rule.walkDecls((decl, i) => {
                    declStr += `${decl.prop}:${decl.value}${i < rule.nodes.length - 1 ? ';' : ''}`;
                });
    
                // 如果有声明，则添加到输出数组
                if (declStr) {
                    // 确保除了第一个规则外，其他规则前都有换行符
                    let formattedRule = `\r\n${selector} {${declStr};}`;
                    console.log('formattedRule: ', formattedRule);
                    outputRules.push(formattedRule);
                } else {
                    // 如果没有声明，则移除该规则
                    rule.remove();
                }
            });
            console.log('outputRules: ',outputRules);
            
            // 更新整个CSS内容
            css.root().nodes = [];
            css.prepend(outputRules.join(``)); // 将所有规则连接成一个字符串并添加到CSS中
        }
    };
}

formatCSSToOnePropertyPerLine.postcss = true;
removeExtraSpaces.postcss = true;
minifyToOneLinePerSelector.postcss = true;

module.exports = class {
    constructor() {

    }

    static init() {
        return new this();
    }
    
    async preLine(editor) {
        console.log('开始目录初始化...');
        let document = editor.document;
        let selection = editor.selection;
        console.log('selection: ',selection);
        // Get the word within the selection
        let word = document.getText(selection);
        console.log('word: ', typeof word);
        
        console.log('formatCSSToOnePropertyPerLine: ',formatCSSToOnePropertyPerLine);
        // let sorted = await postcss([]).process(word, { from: undefined });
        let reversed = await postcss([sorting({
                'properties-order': 'alphabetical'
            }), formatCSSToOnePropertyPerLine(), removeExtraSpaces()]).process(word, { from: undefined });
        
        console.log('reversed: ',reversed);
        editor.edit(editBuilder => {
            editBuilder.replace(selection, reversed.css);
        });
        
        // this.createDir();
        // this.createFile();

        // let tabBar = path.join(this.workspaceFolderFsPath, 'config', 'tab-bar.json');
        // if (!fs.existsSync(tabBar)) {
        //     let jsonData = {};
        //     if (pagesData['tabBar']) {
        //         jsonData["tabBar"] = pagesData['tabBar'];
        //     }
        //     fs.writeFileSync(tabBar, JSON.stringify(jsonData));
        //     console.log('创建文件', tabBar);
        // }

        console.log('目录初始化完成...');
    }
    
    async oneLine(editor) {
        console.log('开始目录初始化...');
        let document = editor.document;
        let selection = editor.selection;
        console.log('selection: ',selection);
        // Get the word within the selection
        let word = document.getText(selection);
        console.log('word: ', typeof word);
        
        let reversed = await postcss([sorting({
                'properties-order': 'alphabetical'
            }), minifyToOneLinePerSelector()]).process(word, { from: undefined, to: undefined });
        
        console.log('reversed: ',reversed);
        editor.edit(editBuilder => {
            editBuilder.replace(selection, reversed.css);
        });
        
        // this.createDir();
        // this.createFile();
    
        // let tabBar = path.join(this.workspaceFolderFsPath, 'config', 'tab-bar.json');
        // if (!fs.existsSync(tabBar)) {
        //     let jsonData = {};
        //     if (pagesData['tabBar']) {
        //         jsonData["tabBar"] = pagesData['tabBar'];
        //     }
        //     fs.writeFileSync(tabBar, JSON.stringify(jsonData));
        //     console.log('创建文件', tabBar);
        // }
    
        console.log('目录初始化完成...');
    }
}